package com.vancouver.knows.ui.fragment.citydiscount;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;

import com.pangu.bean.PageInfo;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.PullListItemBrowser;
import com.pangu.ui.refresh.ARefreshViewController;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.bean.DiscountCategoryInfo;
import com.vancouver.knows.business.bean.HomePageInfo;
import com.vancouver.knows.ui.activity.citydiscount.CityDiscountDetailActivity;
import com.vancouver.knows.ui.activity.citydiscount.CityDiscoutResultActivity;
import com.vancouver.knows.ui.activity.citydiscount.QrCodeBusinessActivity;
import com.vancouver.knows.ui.activity.citynews.CityNewsDetailActivity;
import com.vancouver.knows.ui.activity.event.EventDetailActivity;
import com.vancouver.knows.ui.activity.userpost.UserPostActivity;
import com.vancouver.knows.ui.activity.userpost.UserPostDetailActivity;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchCityDiscountsTaskMark;
import com.vancouver.knows.util.AppUtils;

import java.util.List;

public class CityDiscountListView extends PullListItemBrowser<MainApplication> {

	private BusinessModule bModule;
	private LinearLayout header;
	private String qrCodeBitmapString;
	private int displayedMaxPosition = -1;

	public CityDiscountListView(Context context, ARefreshViewController mController) {
		super(context, mController);
		init();
	}

	public CityDiscountListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		bModule = imContext.getBusinessModule();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		return false;
	}

	public void setQrCode(String qrCode) {
		qrCodeBitmapString = qrCode;
	}

	@Override
	protected View createLoadingView(Context context) {
		RelativeLayout loadingView = (RelativeLayout) super.createLoadingView(context);
		LayoutParams linearLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		ImageView loadingImageView = new ImageView(context);
		loadingImageView.setLayoutParams(linearLayoutParams);
		loadingImageView.setImageResource(R.drawable.loading_business);
		loadingImageView.setScaleType(ImageView.ScaleType.FIT_XY);
		loadingView.addView(loadingImageView, 0);
		return loadingView;
	}

	@Override
	protected BaseAdapter createAdapter() {
		return new CityDiscountsAdapter();
	}

	@Override
	protected void addListHeader(ListView listView) {
		LayoutInflater layoutInflater = LayoutInflater.from(getContext());
		header = (LinearLayout) layoutInflater.inflate(R.layout.discount_header, null);
		listView.addHeaderView(header);
		updateHeader();
	}

	private void updateHeader() {
		DiscountCategoryGridView discountCategoryGridView = (DiscountCategoryGridView) header
				.findViewById(R.id.discount_category_layout);
		discountCategoryGridView.init(bModule.getCacheManager().getDiscountCategoryInfoCache());
	}

	@Override
	protected void setListViewParameters(ListView listView) {
		super.setListViewParameters(listView);
		listView.setDivider(new ColorDrawable(getResources().getColor(R.color.line_color)));
		listView.setDividerHeight(0);
	}

	@Override
	protected void handleLoadNewItems(ATaskMark taskMark) {
		FetchCityDiscountsTaskMark fetchCityDiscountsTaskMark = (FetchCityDiscountsTaskMark) taskMark;
		PageInfo pageInfo = fetchCityDiscountsTaskMark.getPageInfo();
		String userId = "";
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		if (userInfo != null) {
			userId = userInfo.getUserID();
		}
		bModule.getServiceWrapper().fetchCityDiscounts(this, fetchCityDiscountsTaskMark, pageInfo.getNextFrom(),
				pageInfo.getSize(), userId, imContext.latitude, imContext.longitude);

	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		super.receiveResult(taskMark, exception, trackerResult);

		if (taskMark instanceof FetchCityDiscountsTaskMark && taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			updateHeader();
		}
	}

	public class CityDiscountsAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		public CityDiscountsAdapter() {
			inflater = LayoutInflater.from(getContext());
		}

		@Override
		public int getCount() {
			return bModule.getCacheManager().getBusinessHomeDeals().size();
		}

		@Override
		public Object getItem(int position) {
			return bModule.getCacheManager().getBusinessHomeDeals().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == (getCount() - 1)) {
				tryQueryNewItems(true, ATaskMark.TYPE_DEFAULT);
			}

			if (convertView == null) {
				convertView = createItemView(parent);
			}

			HomePageInfo discountInfo = (HomePageInfo) getItem(position);
			if (discountInfo != null) {
				initItemView(convertView, discountInfo, position);
			}

			return convertView;
		}

		private View createItemView(ViewGroup parent) {
			View view = inflater.inflate(R.layout.city_discount_list_view, parent, false);
			ViewHolder viewHolder = new ViewHolder(view);
			view.setTag(viewHolder);

			return view;
		}

		@SuppressLint("NewApi")
		private void initItemView(View convertView, final HomePageInfo discountInfo, final int position) {
			ViewHolder viewHolder = (ViewHolder) convertView.getTag();

			viewHolder.leftLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (discountInfo.getRedirType() != null) {
						String redirType = discountInfo.getRedirType();
						Intent intent = null;
						if ("post".equals(redirType)) {
							intent = new Intent(getContext(), CityNewsDetailActivity.class);
							intent.putExtra("postId", discountInfo.getRedirPostId());
						} else if ("event".equals(redirType)) {
							intent = new Intent(getContext(), EventDetailActivity.class);
							intent.putExtra("postId", discountInfo.getRedirPostId());
						} else if ("business".equals(redirType)) {
							intent = new Intent(getContext(), CityDiscountDetailActivity.class);
							intent.putExtra("postId", discountInfo.getRedirPostId());
						} else if ("web".equals(redirType)) {
							intent = new Intent(Intent.ACTION_VIEW);
							intent.setData(Uri.parse(discountInfo.getRedirUrl()));
						} else if ("userpost_home".equals(redirType)) {
							intent = new Intent(getContext(), UserPostActivity.class);
						} else if ("userpost".equals(redirType)) {
							intent = new Intent(getContext(), UserPostDetailActivity.class);
							intent.putExtra(UserPostDetailActivity.POST_ID_EXTRA, discountInfo.getRedirPostId());
						} else if ("business_list".equals(redirType)) {
							if (bModule.getCacheManager().getDiscountCategoryInfoCache() != null &&
									bModule.getCacheManager().getDiscountCategoryInfoCache().size() >= 0) {
								intent = new Intent(getContext(), CityDiscoutResultActivity.class);
								intent.putExtra("index", getDiscountCategoryPosition(discountInfo.getRedirBusinessCategory(), bModule.getCacheManager().getDiscountCategoryInfoCache()));
								intent.putExtra("category", discountInfo.getRedirBusinessCategory());
								intent.putExtra("subcategory", discountInfo.getRedirBusinessSubcategory());
							}
						}

						if (intent != null) {
							getContext().startActivity(intent);
						}
					} else {
						String postType = discountInfo.getPostType();
						Class cla = null;
						if ("post".equals(postType)) {
							cla = CityNewsDetailActivity.class;
						} else if ("event".equals(postType)) {
							cla = EventDetailActivity.class;
						} else if ("business".equals(postType)) {
							cla = CityDiscountDetailActivity.class;
						}
						if (cla != null) {
							Intent intent = new Intent(getContext(), cla);
							intent.putExtra("postId", discountInfo.getId());
							getContext().startActivity(intent);
						}
					}
				}
			});

			viewHolder.rightLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getContext(), QrCodeBusinessActivity.class);
					intent.putExtra("QR_CODE_BITMAP", qrCodeBitmapString);
					getContext().startActivity(intent);
				}
			});

			viewHolder.title.setText(discountInfo.getPostTitle());
			viewHolder.name.setText(discountInfo.getBusinessName());
			if (discountInfo.getPostAttachmentArray().isEmpty() || discountInfo.getPostAttachmentArray().size() < 3) {
				if (!StringUtil.isEmptyString(discountInfo.getPostAttachmentImage())) {
					Picasso.with(getContext()).load(discountInfo.getPostAttachmentImage()).placeholder(R.drawable.no_image_placeholder)
							.resizeDimen(R.dimen.home_item_width, R.dimen.home_item_height).centerCrop()
							.into(viewHolder.singleImage);
				}
			}

			if (position > displayedMaxPosition) {
				Animation fadeInAnimation = new AlphaAnimation(0, 1);
				fadeInAnimation.setDuration(1000);
				fadeInAnimation.setFillAfter(true);

				Animation translateAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
						Animation.RELATIVE_TO_SELF, 1,Animation.RELATIVE_TO_SELF, 0);
				translateAnimation.setDuration(1000);

				AnimationSet animationSet = new AnimationSet(true);
				animationSet.addAnimation(fadeInAnimation);
				animationSet.addAnimation(translateAnimation);

				viewHolder.layout.startAnimation(animationSet);
				displayedMaxPosition = position;
			}
		}

		public int getDiscountCategoryPosition(String category, List<DiscountCategoryInfo> discountCategoryInfoCache) {
			if (discountCategoryInfoCache == null) {
				return -1;
			}

			if (StringUtil.isEmptyString(category)) {
				return -1;
			}

			for (int index = 0, size = discountCategoryInfoCache.size(); index < size; index++) {
				if (category.equals(discountCategoryInfoCache.get(index).getName())) {
					return index;
				}
			}

			return -1;
		}
		
		public class ViewHolder {

			@Bind(R.id.layout)
			RelativeLayout layout;
			@Bind(R.id.left_layout)
			RelativeLayout leftLayout;
			@Bind(R.id.right_layout)
			RelativeLayout rightLayout;

			@Bind(R.id.title)
			TextView title;
			@Bind(R.id.post_attachment_img)
			ImageView singleImage;
			@Bind(R.id.name)
			TextView name;
			@Bind(R.id.use_text)
			TextView useTxt;

			public ViewHolder(View view) {
				ButterKnife.bind(this, view);
			}

		}

	}

}
